﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Data.Common;
using Data.Enum;
using Data.Model;

namespace DataAccess.SystemManage
{
    /// <summary>
    ///     角色管理
    /// </summary>
    public class SysRole : DbBase, ISysRole
    {
        /// <summary>
        ///     获取指定的角色
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        public ResultInfo<Role> GetRole(int id)
        {
            var result = new ResultInfo<Role> {ResultNumber = ResultEnum.Error};
            try
            {
                string sql = string.Empty;
                var r = new Role();
                if (id > 0)
                {
                    sql = string.Format("select * from role where roleid={0}", id);
                    DataSet ds = ExcuteSqlDataSet(sql);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        result.ResultNumber = ResultEnum.Success;
                        r = new Role(ds.Tables[0].Rows[0]);
                    }
                    else
                    {
                        result.ResultNumber = ResultEnum.Error;
                        result.Describe = "不存在该角色";
                    }
                    result.Obj = r;
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "查询角色失败";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }

            return result;
        }

        /// <summary>
        ///     通过角色名称模糊获取角色的列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="roleName">角色名称</param>
        /// <returns></returns>
        public ResultInfo<PagingDataSet<Role>> GetRoles(int pageIndex, int pageSize, string roleName)
        {
            var result = new ResultInfo<PagingDataSet<Role>>();
            try
            {
                using (SqlCommand myCommand = GetProCommand())
                {
                    myCommand.CommandText = "Common_GetPagingRecords";
                    var fromClause = new StringBuilder();
                    fromClause.AppendFormat("Role R with (nolock)");

                    var whereClause = new StringBuilder();
                    if (!string.IsNullOrEmpty(roleName))
                    {
                        whereClause.Append(string.Format(" and R.rolename like '%{0}%' ", roleName));
                    }
                    if (whereClause.Length > 3)
                    {
                        whereClause.Remove(0, 5);
                    }

                    myCommand.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex - 1;
                    myCommand.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
                    myCommand.Parameters.Add("@FromClause", SqlDbType.VarChar, 1024).Value = fromClause.ToString();
                    myCommand.Parameters.Add("@SelectFields", SqlDbType.VarChar, 512).Value = "R.*";
                    myCommand.Parameters.Add("@WhereClause", SqlDbType.NVarChar, 4000).Value = whereClause.ToString();
                    myCommand.Parameters.Add("@SortField", SqlDbType.VarChar, 256).Value = "R.RoleID";
                    myCommand.Parameters.Add("@SortFieldIsDesc", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@ReturnRecordCount", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@MaxRecords", SqlDbType.Int).Value = int.MaxValue;
                    myCommand.Parameters.Add("@TotalRecords", SqlDbType.Int).Direction = ParameterDirection.Output;
                    myCommand.Parameters.Add("@ReverseOrder", SqlDbType.Bit).Direction = ParameterDirection.Output;

                    var list = new List<Role>();
                    var dataSet = new DataSet();
                    var da = new SqlDataAdapter(myCommand);
                    da.Fill(dataSet);

                    if (dataSet != null)
                    {
                        foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                        {
                            var jshAccount = new Role(dataRow);
                            if (jshAccount.TranByConstructFlag)
                            {
                                list.Add(jshAccount);
                            }
                        }
                    }

                    int totalRecords = Convert.ToInt32(myCommand.Parameters["@TotalRecords"].Value);
                    bool reverseOrder = Convert.ToBoolean(myCommand.Parameters["@ReverseOrder"].Value);

                    if (reverseOrder)
                        list.Reverse();

                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = new PagingDataSet<Role>
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        Records = list,
                        TotalRecords = totalRecords
                    };
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        ///     创建或更新角色信息
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public ResultInfo<int> CreateUpdateRole(Role role)
        {
            var result = new ResultInfo<int>();
            try
            {
                string sql = string.Empty;
                if (role != null)
                {
                    if (role.Roleid > 0)
                    {
                        sql =
                            string.Format(
                                "UPDATE Role SET [RoleName]='{0}',[createtime]=getdate() where [RoleID]={1} select {1} id",
                                role.Rolename, role.Roleid);
                    }
                    else
                    {
                        string check = string.Format("select roleid from role where rolename='{0}'", role.Rolename);
                        DataSet dt = ExcuteSqlDataSet(check);
                        if (dt != null && dt.Tables[0].Rows.Count > 0)
                        {
                            result.ResultNumber = ResultEnum.Error;
                            result.Describe = "已经存在同名角色，请重新输入";
                        }
                        else
                        {
                            sql =
                                string.Format(
                                    "insert into Role([RoleName],[createtime]) values('{0}',getdate()) select @@identity id",
                                    role.Rolename);
                        }
                    }
                    if (!string.IsNullOrEmpty(sql))
                    {
                        DataSet dataSet = ExcuteSqlDataSet(sql);
                        if (dataSet != null && dataSet.Tables[0].Rows.Count == 1)
                        {
                            int temp = Convert.ToInt32(dataSet.Tables[0].Rows[0]["id"]);
                            if (temp > 0)
                            {
                                result.ResultNumber = ResultEnum.Success;
                                result.Obj = temp;
                            }
                            else
                            {
                                result.ResultNumber = ResultEnum.Error;
                                result.Describe = "更新数据失败";
                            }
                        }
                    }
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "请输入有效数据";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        ///     删除指定角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultInfo<bool> DeleteRole(int id)
        {
            var result = new ResultInfo<bool> {ResultNumber = ResultEnum.Error};
            try
            {
                string sql = string.Format("delete from Role where roleid={0}", id);
                int temp = ExcuteSql(sql);
                if (temp > 0)
                {
                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = true;
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Obj = false;
                }
            }
            catch (Exception)
            {
            }
            return result;
        }

        /// <summary>
        ///     根据角色id获取该角色具有的权限
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        public ResultInfo<PagingDataSet<RolePrivilege>> GetRolePrivileges(int pageIndex, int pageSize, int roleId)
        {
            var result = new ResultInfo<PagingDataSet<RolePrivilege>>();
            //if (roleId > 0)
            //{
                try
                {
                    using (SqlCommand myCommand = GetProCommand())
                    {
                        myCommand.CommandText = "Common_GetPagingRecords";
                        var fromClause = new StringBuilder();
                        fromClause.AppendFormat("RolePrivilege R with (nolock)");

                        var whereClause = new StringBuilder();
                        if (roleId > 0)
                        {
                            whereClause.Append(string.Format(" and R.RoleID = {0} ", roleId));
                        }
                        if (whereClause.Length > 3)
                        {
                            whereClause.Remove(0, 5);
                        }

                        myCommand.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex - 1;
                        myCommand.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
                        myCommand.Parameters.Add("@FromClause", SqlDbType.VarChar, 1024).Value = fromClause.ToString();
                        myCommand.Parameters.Add("@SelectFields", SqlDbType.VarChar, 512).Value = "R.*";
                        myCommand.Parameters.Add("@WhereClause", SqlDbType.NVarChar, 4000).Value =
                            whereClause.ToString();
                        myCommand.Parameters.Add("@SortField", SqlDbType.VarChar, 256).Value = "R.id";
                        myCommand.Parameters.Add("@SortFieldIsDesc", SqlDbType.Bit).Value = true;
                        myCommand.Parameters.Add("@ReturnRecordCount", SqlDbType.Bit).Value = true;
                        myCommand.Parameters.Add("@MaxRecords", SqlDbType.Int).Value = int.MaxValue;
                        myCommand.Parameters.Add("@TotalRecords", SqlDbType.Int).Direction = ParameterDirection.Output;
                        myCommand.Parameters.Add("@ReverseOrder", SqlDbType.Bit).Direction = ParameterDirection.Output;

                        var list = new List<RolePrivilege>();
                        var dataSet = new DataSet();
                        var da = new SqlDataAdapter(myCommand);
                        da.Fill(dataSet);

                        if (dataSet != null)
                        {
                            foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                            {
                                var jshAccount = new RolePrivilege(dataRow);
                                if (jshAccount.TranByConstructFlag)
                                {
                                    list.Add(jshAccount);
                                }
                            }
                        }

                        int totalRecords = Convert.ToInt32(myCommand.Parameters["@TotalRecords"].Value);
                        bool reverseOrder = Convert.ToBoolean(myCommand.Parameters["@ReverseOrder"].Value);

                        if (reverseOrder)
                            list.Reverse();

                        result.ResultNumber = ResultEnum.Success;
                        result.Obj = new PagingDataSet<RolePrivilege>
                        {
                            PageIndex = pageIndex,
                            PageSize = pageSize,
                            Records = list,
                            TotalRecords = totalRecords
                        };
                    }
                }
                catch (Exception e)
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = e.Message;
                }
            //}
            //else
            //{
            //    result.ResultNumber = ResultEnum.Error;
            //    result.Describe = "选取的角色无效";
            //}
            return result;
        }

        /// <summary>
        ///     创建或更新角色权限信息
        /// </summary>
        /// <param name="rp"></param>
        /// <returns></returns>
        public ResultInfo<int> CreateUpdateRolePrivilege(RolePrivilege rp)
        {
            var result = new ResultInfo<int>();
            try
            {
                string sql = string.Empty;
                if (rp != null)
                {
                    if (rp.Id > 0)
                    {
                        sql =
                            string.Format(
                                "UPDATE RolePrivilege SET [RoleID]={0},[PrivilegeID]={1},[rolename]='{3}',[PrivilegeName]='{4}' where [ID]={2}, select {2} id",
                                rp.Roleid, rp.Privilegeid, rp.Id, rp.rolename, rp.Privilegename);
                    }
                    else
                    {
                        string check = string.Format(
                            "select id from RolePrivilege where roleid={0} and privilegeid={1}", rp.Roleid,
                            rp.Privilegeid);
                        DataSet dt = ExcuteSqlDataSet(check);
                        if (dt != null && dt.Tables[0].Rows.Count > 0)
                        {
                            result.ResultNumber = ResultEnum.Error;
                            result.Describe = "已经存在相同权限角色对应关系，请重新输入";
                        }
                        else
                        {
                            sql =
                                string.Format(
                                    "insert into RolePrivilege([RoleID],[PrivilegeID],[rolename],[PrivilegeName]) values({0},{1},'{2}','{3}') select @@identity id",
                                    rp.Roleid, rp.Privilegeid, rp.rolename, rp.Privilegename);
                        }
                    }
                    if (!string.IsNullOrEmpty(sql))
                    {
                        DataSet dataSet = ExcuteSqlDataSet(sql);
                        if (dataSet != null && dataSet.Tables[0].Rows.Count == 1)
                        {
                            int temp = Convert.ToInt32(dataSet.Tables[0].Rows[0]["id"]);
                            if (temp > 0)
                            {
                                result.ResultNumber = ResultEnum.Success;
                                result.Obj = temp;
                            }
                            else
                            {
                                result.ResultNumber = ResultEnum.Error;
                                result.Describe = "更新数据失败";
                            }
                        }
                    }
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "请输入有效数据";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        ///     删除指定角色权限记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultInfo<bool> DeleteRolePrivilege(int id)
        {
            var result = new ResultInfo<bool> {ResultNumber = ResultEnum.Error};
            try
            {
                string sql = string.Format("delete from RolePrivilege where id={0}", id);
                int temp = ExcuteSql(sql);
                if (temp > 0)
                {
                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = true;
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Obj = false;
                }
            }
            catch (Exception)
            {
            }
            return result;
        }

        /// <summary>
        ///     获取角色还没有的权限
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ResultInfo<PagingDataSet<Privilege>> GetRoleUnPrivileges(int roleid, int pageIndex, int pageSize)
        {
            var result = new ResultInfo<PagingDataSet<Privilege>>();
            try
            {
                using (SqlCommand myCommand = GetProCommand())
                {
                    myCommand.CommandText = "Common_GetPagingRecords";
                    var fromClause = new StringBuilder();
                    fromClause.AppendFormat("Privilege R with (nolock)");

                    var whereClause = new StringBuilder();
                    if (roleid > 0)
                    {
                        whereClause.Append(
                            string.Format(
                                " and privilegeid not in (select rp.privilegeid from roleprivilege rp where rp.roleid={0}) ",
                                roleid));
                    }
                    if (whereClause.Length > 3)
                    {
                        whereClause.Remove(0, 5);
                    }

                    myCommand.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex - 1;
                    myCommand.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
                    myCommand.Parameters.Add("@FromClause", SqlDbType.VarChar, 1024).Value = fromClause.ToString();
                    myCommand.Parameters.Add("@SelectFields", SqlDbType.VarChar, 512).Value = "R.*";
                    myCommand.Parameters.Add("@WhereClause", SqlDbType.NVarChar, 4000).Value = whereClause.ToString();
                    myCommand.Parameters.Add("@SortField", SqlDbType.VarChar, 256).Value = "R.PrivilegeID";
                    myCommand.Parameters.Add("@SortFieldIsDesc", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@ReturnRecordCount", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@MaxRecords", SqlDbType.Int).Value = int.MaxValue;
                    myCommand.Parameters.Add("@TotalRecords", SqlDbType.Int).Direction = ParameterDirection.Output;
                    myCommand.Parameters.Add("@ReverseOrder", SqlDbType.Bit).Direction = ParameterDirection.Output;

                    var list = new List<Privilege>();
                    var dataSet = new DataSet();
                    var da = new SqlDataAdapter(myCommand);
                    da.Fill(dataSet);

                    if (dataSet != null)
                    {
                        foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                        {
                            var jshAccount = new Privilege(dataRow);
                            if (jshAccount.TranByConstructFlag)
                            {
                                list.Add(jshAccount);
                            }
                        }
                    }

                    int totalRecords = Convert.ToInt32(myCommand.Parameters["@TotalRecords"].Value);
                    bool reverseOrder = Convert.ToBoolean(myCommand.Parameters["@ReverseOrder"].Value);

                    if (reverseOrder)
                        list.Reverse();

                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = new PagingDataSet<Privilege>
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        Records = list,
                        TotalRecords = totalRecords
                    };
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }
    }
}